/*
 *  Copyright 2008-2010 the original author or authors.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.openaecfm.spf.model;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringParameter implements UntypedParameter {

    public final static String UTF_8 = "UTF-8";
    public final static String ISO_8859_1 = "ISO-8859-1";
    private String value;
    protected final Log logger = LogFactory.getLog(getClass());

    public String getStringParameterValue() {
        return value;
    }

    public void setStringParameterValue(String value) {
        this.value = value;
    }

    public StringParameter() {
    }

    public StringParameter(String value, String charset) {
        if (ISO_8859_1.equalsIgnoreCase(charset)) {
            this.value = value;
        } else {
            try {
                String iso_8859_1 = new String(value.getBytes(charset), ISO_8859_1);
                iso_8859_1 = replace(iso_8859_1, "'", "''");
                iso_8859_1 = replace(iso_8859_1, "\\\\", "\\\\\\\\");
                iso_8859_1 = "'" + iso_8859_1 + "'";

                this.value = iso_8859_1;
            } catch (UnsupportedEncodingException ex) {
                logger.error(ex);
            }
        }
    }

    @Override
    public String toString() {
        return value;
    }

    public String toUTF8() {
        try {
            String iso_8859_1 = value.substring(1, value.length() - 1);
            iso_8859_1 = replace(iso_8859_1, "''", "'");
            iso_8859_1 = replace(iso_8859_1, "\\\\\\\\", "\\\\");

            return new String(iso_8859_1.getBytes(ISO_8859_1), UTF_8);
        } catch (UnsupportedEncodingException ex) {
            logger.error(ex);
            return null;
        }
    }

    public static String replace(String str, String regex, String newStr) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        String s = m.replaceAll(newStr);

        return s;
    }

    @Override
    public final NodeType getNodeType() {
        return NodeType.STRING;
    }

	@Override
	public void addChild(Node n) {}
}
